<script setup lang="ts">
import { createVNode, onMounted, reactive, ref } from 'vue'
import { UserOutlined, ExclamationCircleOutlined } from '@ant-design/icons-vue'
import { useLoginUserStore } from '@/stores/useLoginUserStore.ts'
import { userEditInfo, userSendCode, userVerifyCode } from '@/api/userController.ts'
import { message, Modal } from 'ant-design-vue'

const formState = reactive<any>({
  userId: '',
  userAccount: '',
  userAvatar: '',
  userEmail: '',
  userName: '',
  userPassword: '',
  userProfile: '',
  userVerifyCode: '',
})

const bindEmailFormState = reactive<any>({
  userEmail: '',
  userVerifyCode: '',
})

const bindPasswordFormState = reactive<any>({
  userPassword: '',
  checkPassword: '',
})

const loginUserStore = useLoginUserStore()

const fetchUserInfo = async () => {
  const loginUserStore = useLoginUserStore()
  formState.userId = loginUserStore.loginUser.id
  formState.userAccount = loginUserStore.loginUser.userAccount
  formState.userName = loginUserStore.loginUser.userName
  formState.userProfile = loginUserStore.loginUser.userProfile
  formState.userAvatar = loginUserStore.loginUser.userAvatar
  formState.userEmail = loginUserStore.loginUser.userEmail
}

const openAvatarModel = ref<boolean>(false)
const openEmailModel = ref<boolean>(false)
const picture = ref()
const loading = ref<boolean>(false)
const isButtonDisabled = ref<boolean>(false)
const countdown = ref<number>(60)
const buttonText = ref<string>('获取验证码')
const openPasswordModel = ref<boolean>(false)

onMounted(() => {
  fetchUserInfo()
})

const editUserAvatar = () => {
  openAvatarModel.value = true
  picture.value = undefined
}

/**
 * 提交表单
 * @param values
 */
const handleSubmit = async (values: any) => {
  const res = await userEditInfo(values)
  // 修改成功，把修改态保存到全局状态中
  if (res.data.code === 0 && res.data.data) {
    await loginUserStore.fetchLoginUser()
    message.success('修改成功')
  } else {
    message.error('修改失败，' + res.data.message)
  }
}

const onSuccess = (newPicture: any) => {
  picture.value = newPicture
}

const handleAvatarOk = async () => {
  loading.value = true
  const url = picture.value?.url
  const userAccount = loginUserStore.loginUser.userAccount
  const res = await userEditInfo({ userAccount, userAvatar: url })
  if (res.data.code === 0 && res.data.data) {
    message.success('修改成功')
    await loginUserStore.fetchLoginUser()
    openAvatarModel.value = false
  } else {
    message.error('修改失败，' + res.data.message)
  }
  await fetchUserInfo()
  loading.value = false
  openAvatarModel.value = false
}

const handleAvatarCancel = () => {
  openAvatarModel.value = false
}

const handleEmailCancel = () => {
  openEmailModel.value = false
}

const bindEmail = () => {
  openEmailModel.value = true
}

const userSendVerifyCode = async () => {
  // 判断邮箱是否为空
  if (bindEmailFormState.userEmail === '') {
    message.error('请先输入邮箱')
    return
  }
  // 验证邮箱格式是否正确
  const reg = /^[a-zA-Z0-9_-]+@[a-zA-Z0-9_-]+(\.[a-zA-Z0-9_-]+)+$/
  if (!reg.test(bindEmailFormState.userEmail)) {
    message.error('请输入正确的邮箱格式')
  }
  const res = await userSendCode({
    ...bindEmailFormState,
    userAccount: formState.userAccount,
  })
  if (res.data.code === 0 && res.data.data) {
    message.success('验证码发送成功')
  } else {
    message.error('验证码发送失败，' + res.data.message)
  }
  isButtonDisabled.value = true
  const timer = setInterval(() => {
    countdown.value -= 1
    buttonText.value = `${countdown.value} 秒后重新获取`
    if (countdown.value === 0) {
      clearInterval(timer)
      isButtonDisabled.value = false
      countdown.value = 60
      buttonText.value = '获取验证码'
    }
  }, 1000)
}

const handleEmailOk = async () => {
  // 判断邮箱是否为空
  if (bindEmailFormState.userEmail === null || bindEmailFormState.userEmail === '') {
    message.error('请先输入邮箱')
    return
  }
  // 判断验证码是否为空
  if (bindEmailFormState.userVerifyCode === null || bindEmailFormState.userVerifyCode === '') {
    message.error('请先输入验证码')
    return
  }
  loading.value = true
  // 判断验证码是否正确
  const res = await userVerifyCode({
    ...bindEmailFormState,
    userAccount: formState.userAccount,
  })
  if (res.data.code === 0 && res.data.data) {
    const res = await userEditInfo({
      ...bindEmailFormState,
      userAccount: formState.userAccount,
    })
    if (res.data.code === 0 && res.data.data) {
      message.success('绑定成功')
      await loginUserStore.fetchLoginUser()
      formState.userEmail = bindEmailFormState.userEmail
    } else {
      message.error('绑定失败，' + res.data.message)
    }
    openEmailModel.value = false
  } else {
    message.error('验证码错误')
  }
  loading.value = false
}

const unbindEmail = async () => {
  Modal.confirm({
    title: '你是否要解绑该邮箱',
    icon: createVNode(ExclamationCircleOutlined),
    content:
      '解绑当前邮箱会导致密码找回渠道失效，若忘记密码可能无法登录；同时失去邮箱这一关键安全验证手段，账号遭遇异常时难以及时预警和处理，被盗风险升高，且可能错过平台发送的重要账号通知，建议解绑前确保已绑定其他有效安全验证方式。',
    okText: '确认',
    okType: 'danger',
    cancelText: '取消',
    onOk() {
      userEditInfo({ userAccount: formState.userAccount, userEmail: '' }).then((res) => {
        if (res.data.code === 0 && res.data.data) {
          message.success('解绑成功')
          formState.userEmail = ''
        } else {
          message.error('解绑失败，' + res.data.message)
        }
      })
    },
  })
}

const updatePassword = () => {
  openPasswordModel.value = true
}

const handlePasswordOk = async () => {
  if (
    bindPasswordFormState.userPassword === undefined ||
    bindPasswordFormState.userPassword === ''
  ) {
    message.error('请输入密码')
    return
  }
  if (
    bindPasswordFormState.checkPassword === undefined ||
    bindPasswordFormState.checkPassword === ''
  ) {
    message.error('请再次输入密码')
    return
  }
  if (bindPasswordFormState.userPassword !== bindPasswordFormState.checkPassword) {
    message.error('两次密码不一致')
    return
  }
  loading.value = true
  formState.userPassword = bindPasswordFormState.userPassword
  const res = await userEditInfo(formState)
  if (res.data.code === 0 && res.data.data) {
    message.success('修改成功')
    openPasswordModel.value = false
    bindPasswordFormState.userPassword = ''
    bindPasswordFormState.checkPassword = ''
  } else {
    message.error('修改失败，' + res.data.message)
  }
  loading.value = false
}
</script>

<template>
  <div id="userInfoPage">
    <h2 class="title">智慧农业平台 - 个人信息</h2>
    <div class="desc">农业数据监控AI赋能平台</div>
    <a-form :model="formState" name="basic" autocomplete="off" @finish="handleSubmit">
      <a-form-item class="userAvatar" name="userAvatar">
        <a-flex style="align-items: center">
          <div style="width: 50px">头像 :</div>
          <a-avatar
            :size="{ xs: 24, sm: 32, md: 60, lg: 80, xl: 100, xxl: 128 }"
            :src="formState.userAvatar"
            @click="editUserAvatar"
          >
            <template #icon>
              <UserOutlined />
            </template>
          </a-avatar>
        </a-flex>
      </a-form-item>
      <a-form-item name="userId">
        <a-flex style="align-items: center; display: flex; gap: 8px">
          <div style="width: 50px">ID :</div>
          <a-typography-link copyable>
            {{ formState.userId }}
          </a-typography-link>
        </a-flex>
      </a-form-item>
      <a-form-item name="userAccount">
        <a-flex style="align-items: center; display: flex; gap: 8px">
          <div style="width: 50px">账号 :</div>
          <span>{{ formState.userAccount }}</span>
        </a-flex>
      </a-form-item>
      <a-form-item name="userName" :rules="[{ required: true, message: '昵称不能为空' }]">
        <a-flex justify="space-between" style="align-items: center">
          <div style="width: 50px">昵称 :</div>
          <a-input v-model:value="formState.userName" placeholder="请输入昵称" />
        </a-flex>
      </a-form-item>
      <a-form-item name="userProfile">
        <div style="width: 70px; margin-bottom: 16px">个人简介:</div>
        <a-textarea
          v-model:value="formState.userProfile"
          placeholder="请输入简介"
          :rows="4"
          :maxlength="300"
          show-count
          allow-clear
        />
      </a-form-item>
      <a-form-item name="userEmail">
        <a-flex style="align-items: center; display: flex; gap: 8px">
          <div style="width: 50px">邮箱 :</div>
          <template v-if="formState.userEmail">
            <span>{{ formState.userEmail }}</span>
            <a-button type="text" danger @click="unbindEmail">解绑</a-button>
          </template>
          <a-button type="primary" v-else @click="bindEmail">绑定邮箱</a-button>
        </a-flex>
      </a-form-item>
      <a-form-item name="userPassword">
        <a-flex style="align-items: center; display: flex; gap: 8px">
          <div style="width: 50px">密码 :</div>
          <a-button danger @click="updatePassword">修改密码</a-button>
        </a-flex>
      </a-form-item>
      <a-form-item>
        <a-button type="primary" html-type="submit" style="width: 100%">保存</a-button>
      </a-form-item>
    </a-form>
    <a-modal v-model:open="openAvatarModel" title="上传头像" @ok="handleAvatarOk">
      <template #footer>
        <a-button key="back" @click="handleAvatarCancel">取消</a-button>
        <a-button key="submit" type="primary" :loading="loading" @click="handleAvatarOk"
          >确认
        </a-button>
      </template>
    </a-modal>
    <a-modal v-model:open="openEmailModel" title="绑定邮箱" @ok="handleEmailOk">
      <a-form
        :model="bindEmailFormState"
        name="basic"
        label-align="left"
        autocomplete="off"
        @finish="handleEmailOk"
      >
        <a-form-item name="userEmail" :rules="[{ required: true, message: '请输入邮箱' }]">
          <a-input
            v-model:value="bindEmailFormState.userEmail"
            placeholder="请输入邮箱"
            allow-clear
          />
        </a-form-item>
        <a-form-item name="userVerifyCode" :rules="[{ required: true, message: '请输入验证码' }]">
          <a-input-group compact>
            <a-input
              v-model:value="bindEmailFormState.userVerifyCode"
              style="width: calc(100% - 200px)"
              allow-clear
            />
            <a-button type="primary" :disabled="isButtonDisabled" @click="userSendVerifyCode">
              {{ buttonText }}
            </a-button>
          </a-input-group>
        </a-form-item>
      </a-form>
      <template #footer>
        <a-button key="back" @click="handleEmailCancel">取消</a-button>
        <a-button key="submit" type="primary" :loading="loading" @click="handleEmailOk"
          >确认
        </a-button>
      </template>
    </a-modal>
    <a-modal
      v-model:open="openPasswordModel"
      :confirm-loading="loading"
      title="修改密码"
      :cancelText="'取消'"
      :ok-text="'修改'"
      @ok="handlePasswordOk"
    >
      <a-form
        :model="bindPasswordFormState"
        name="basic"
        label-align="left"
        autocomplete="off"
        @finish="handlePasswordOk"
      >
        <a-form-item
          name="userPassword"
          :rules="[
            { required: true, message: '请输入密码' },
            { min: 8, message: '密码不能小于 8 位' },
          ]"
        >
          <a-input-password
            v-model:value="bindPasswordFormState.userPassword"
            placeholder="请输入密码"
          />
        </a-form-item>
        <a-form-item
          name="checkPassword"
          :rules="[
            { required: true, message: '请输入确认密码' },
            { min: 8, message: '确认密码不能小于 8 位' },
          ]"
        >
          <a-input-password
            v-model:value="bindPasswordFormState.checkPassword"
            placeholder="请输入确认密码"
          />
        </a-form-item>
      </a-form>
    </a-modal>
  </div>
</template>

<style scoped>
#userInfoPage {
  max-width: 400px;
  margin: 0 auto;
}

.userAvatar :hover {
  cursor: pointer;
}

.title {
  text-align: center;
  margin-bottom: 16px;
}

.desc {
  text-align: center;
  color: #bbb;
  margin-bottom: 16px;
}
</style>
